<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="t('routes.demo.documentWorkPlace.directoryWorkAssign')"
      @register="register"
      @ok="handleSubmit"
      :destroyOnClose="true"
      :minHeight="450"
      :width="1200"
    >
      <BasicForm @register="registerForm" />
      <Divider style="width: 100%" />
      <BasicTable @register="registerTable" :data-source="dataList" />
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form';
  import { getDirAssignColumns, getDirAssignModal } from './tableData';
  import { Divider } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { workAssign } from '/@/api/demo/document';

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const holderName = ref<string>('');
  const holder = ref<string>('');
  const dataList = ref<any[]>([]);
  const selectedList = ref<any[]>([]);

  // 提交
  async function handleSubmit() {
    closeModal();
  }

  const onSubmit = () => {
    if (holder.value === getFieldsValue().receiver) {
      createMessage.error(t('routes.demo.documentManager.cannotTransferToSelf'));
    } else {
      workAssign(getFieldsValue().receiver, selectedList.value).then(() => {
        createMessage.success(t('routes.demo.documentManager.transferSuccess'));
        closeModal();
      });
    }
  };

  const onSelectChange = (_selectedRowKeys, selectedRows) => {
    selectedList.value = selectedRows;
  };

  // 初始化弹窗
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    holder.value = data.holder;
    holderName.value = data.holderName;
    dataList.value = data.fileList;
    setFieldsValue({ ...data });
  });

  // 表格初始化
  const [registerTable] = useTable({
    columns: getDirAssignColumns(),
    rowSelection: { type: 'checkbox', onChange: onSelectChange },
    bordered: true,
    useSearchForm: false,
    showIndexColumn: false,
    showTableSetting: true, // 显示表格设置工具
    tableSetting: { fullScreen: true }, // 表格设置工具配置
    pagination: { pageSize: 5, pageSizeOptions: ['5', '10', '15', '20'], defaultPageSize: 5 },
    canResize: false,
    striped: false,
  });

  // 初始化表单
  const [registerForm, { resetFields, setFieldsValue, getFieldsValue }] = useForm({
    labelCol: { span: 6 },
    wrapperCol: { span: 12 },
    schemas: getDirAssignModal(),
    showResetButton: false,
    showSubmitButton: true,
    submitButtonOptions: {
      text: t('routes.demo.documentManager.handover'),
      onClick: onSubmit,
    },
  });
</script>
